package com.rockcent.third.helper;

import com.rockcent.mall.lib.domain.IntegrationChannel;
import com.rockcent.mall.lib.domain.UserInfo;
import com.rockcent.mall.lib.dto.ThirdPartyUserInfoDto;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangjh on 2017/1/12.
 */
@Component
public class ThirdPartyUserHelper {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取第三方用户登录的token
     *
     * @param userInfo
     * @return
     */
    public String getThirdUserToken(ThirdPartyUserInfoDto userInfo) {
        return DigestUtils.md5Hex(userInfo.getAppKey() + userInfo.getAppSecret() + java.sql.Date.from(Instant.now()).getTime());
    }

    /**
     * @param thirdPartyUserInfoDto
     * @param request
     * @param integrationChannel
     * @return
     */
    public ThirdPartyUserInfoDto setSession(ThirdPartyUserInfoDto thirdPartyUserInfoDto, HttpServletRequest request, IntegrationChannel integrationChannel) {
        String userToken = getThirdUserToken(thirdPartyUserInfoDto);
        redisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + userToken).set(integrationChannel.getId().toString());
        Long userTokenTimer = 2 * 60 * 60L; // 2个小时 生命周期
        redisTemplate.expire(UserInfo.REDIS_USER_TOKEN_PREFIX + userToken, userTokenTimer, TimeUnit.SECONDS);
        ThirdPartyUserInfoDto userInfoDto = new ThirdPartyUserInfoDto();
        userInfoDto.setExpiresIn(userTokenTimer);
        userInfoDto.setAccessToken(userToken);
        return userInfoDto;
    }


}
